package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.*;
import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.vo.ExportProductResult;
import cn.itcast.vo.ExportResult;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

// 引入dubbo提供的注解，用来发布服务
@Service(timeout = 100000)
public class ExportServiceImpl implements ExportService {

    // 注入报运单信息
    @Autowired
    private ExportDao exportDao;
    @Autowired
    private ExportProductDao exportProductDao;
    @Autowired
    private ExtEproductDao extEproductDao;

    // 注入购销合同信息
    @Autowired
    private ContractDao contractDao;
    @Autowired
    private ContractProductDao contractProductDao;
    @Autowired
    private ExtCproductDao extCproductDao;

    @Override
    public PageInfo<Export> findByPage(
            ExportExample exportExample, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Export> list = exportDao.selectByExample(exportExample);
        return new PageInfo<>(list);
    }
    @Override
    public Export findById(String id) {
        return exportDao.selectByPrimaryKey(id);
    }

    /**
     * 对象拷贝：
     *    org.apache.commons.beanutils.BeanUtils.copyProperties(目标对象,数据源);
     *    org.springframework.beans.BeanUtils.copyProperties(数据源,目标对象)
     */
    @Override
    public void save(Export export) {
        //1. 设置报运单id、商品数量、附件数量、状态
        export.setId(UUID.randomUUID().toString());
        export.setState(0);

        // 获取购销合同id
        String contractIds = export.getContractIds();
        String[] array = contractIds.split(",");
        List<String> contractIdList = Arrays.asList(array);

        //2. 根据购销合同id，获取合同号；修改购销合同状态为2表示已经生成报运
        ContractExample contractExample = new ContractExample();
        contractExample.createCriteria().andIdIn(contractIdList);
        List<Contract> contractList = contractDao.selectByExample(contractExample);
        if (contractIdList == null || contractIdList.size() == 0){
            throw new RuntimeException("购销合同id为空！");
        }
        // 保存合同号
        String contractNos = "";
        // 遍历购销合同
        for (Contract contract : contractList) {
            contractNos = contract.getContractNo() + " ";
            // 修改购销合同状态为2表示已经生成报运
            contract.setState(2);
            contractDao.updateByPrimaryKeySelective(contract);
        }
        // 设置合同号
        export.setCustomerContract(contractNos);

        // 定义map存储：货物id、商品id
        Map<String,String> idMap = new HashMap<>();

        //3. 根据购销合同id查询所有货物，再把货物数据录入到商品表
        ContractProductExample cpExample = new ContractProductExample();
        cpExample.createCriteria().andContractIdIn(contractIdList);
        List<ContractProduct> contractProductList = contractProductDao.selectByExample(cpExample);
        if (contractProductList != null && contractProductList.size()>0) {
            // 遍历货物
            for (ContractProduct contractProduct : contractProductList) {
                // 【创建商品对象】
                ExportProduct exportProduct = new ExportProduct();
                // 【封装商品对象】
                // 导入的包：org.springframework.beans
                BeanUtils.copyProperties(contractProduct,exportProduct);
                // 设置商品id
                exportProduct.setId(UUID.randomUUID().toString());
                // 设置报运单id
                exportProduct.setExportId(export.getId());
                // 【保存商品对象】
                exportProductDao.insertSelective(exportProduct);

                // 添加数据：key是货物id； value是商品id
                idMap.put(contractProduct.getId(),exportProduct.getId());
            }
        }

        //4. 根据购销合同id查询所有附件，再把货物附件录入到商品附件表
        ExtCproductExample extCproductExample = new ExtCproductExample();
        extCproductExample.createCriteria().andContractIdIn(contractIdList);
        List<ExtCproduct> extCproductList = extCproductDao.selectByExample(extCproductExample);
        if (extCproductList != null && extCproductList.size()>0) {
            // 遍历购销合同附件
            for (ExtCproduct extCproduct : extCproductList) {
                //【创建商品附件】
                ExtEproduct extEproduct = new ExtEproduct();
                //【封装商品附件】
                BeanUtils.copyProperties(extCproduct,extEproduct);
                // --->1. 设置附件id
                extEproduct.setId(UUID.randomUUID().toString());
                // --->2. 设置报运单id
                extEproduct.setExportId(export.getId());
                /**
                 * --->3. 设置报运单的商品id
                 * 已知条件： extCproduct.getContractProductId() 货物id
                 * 求解：    商品id？
                 */
                extEproduct.setExportProductId(idMap.get(extCproduct.getContractProductId()));
                //【保存商品附件】
                extEproductDao.insertSelective(extEproduct);
            }
        }

        //5. 添加报运单（商品、附件已经添加）
        export.setProNum(contractProductList.size());
        export.setExtNum(extCproductList.size());
        exportDao.insertSelective(export);
    }

    @Override
    public void update(Export export) {
        //1. 修改报运的商品
        List<ExportProduct> exportProducts = export.getExportProducts();
        if (exportProducts != null && exportProducts.size() > 0){
            for (ExportProduct exportProduct : exportProducts) {
                exportProductDao.updateByPrimaryKeySelective(exportProduct);
            }
        }
        //2. 修改报运单
        exportDao.updateByPrimaryKeySelective(export);

    }

    @Override
    public void delete(String id) {
        exportDao.deleteByPrimaryKey(id);
    }

    @Override
    public void updateExport(ExportResult exportResult) {
        //1. 修改报运单 (状态、备注)
        Export export = new Export();
        export.setId(exportResult.getExportId());
        export.setState(exportResult.getState());
        export.setRemark(exportResult.getRemark());
        exportDao.updateByPrimaryKeySelective(export);

        //2. 修改报运商品
        Set<ExportProductResult> products = exportResult.getProducts();
        if (products != null && products.size() > 0) {
            for (ExportProductResult result : products) {
                ExportProduct exportProduct = new ExportProduct();
                exportProduct.setId(result.getExportProductId());
                exportProduct.setTax(result.getTax());
                exportProductDao.updateByPrimaryKeySelective(exportProduct);
            }
        }
    }

    @Override
    public List<Export> findByIds(ExportExample exportExample) {
        List<Export> exportList = exportDao.selectByExample(exportExample);
        return exportList;
    }

}
